package com.leyou.trade.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;
    @Autowired
    private WXPayConfigImpl payConfig;

    public String getPayUrl(Long orderId, Long totalFee) {
        // 5个请求参数：
        Map<String, String> data = new HashMap<>();
        data.put("body", "乐优商城商品");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());
        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        data.put("trade_type", payConfig.getTradeType());

        try {
            // 下单
            Map<String, String> resp = wxPay.unifiedOrder(data);
            // 判断通信标示
            checkReturnCode(resp);
            // 判断业务标示
            checkResultCode(resp);
            // 签名验证
            boolean isValid = wxPay.isResponseSignatureValid(resp);
            if (!isValid) {
                // 签名无效
                throw new RuntimeException("签名错误");
            }
            // 获取支付链接并返回
            String url = resp.get("code_url");
            if (StringUtils.isBlank(url)) {
                // 获取支付链接为空
                throw new RuntimeException("支付链接为空！");
            }
            return url;
        } catch (Exception e) {
            // 微信下单失败！
            log.error("微信下单失败，原因：" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void checkResultCode(Map<String, String> resp) {
        if ("FAIL".equals(resp.get("result_code"))) {
            // 业务异常
            throw new RuntimeException(resp.get("err_code"));
        }
    }

    public void checkReturnCode(Map<String, String> resp) {
        // 判断通信标示
        if ("FAIL".equals(resp.get("return_code"))) {
            // 通信异常
            throw new RuntimeException(resp.get("return_msg"));
        }
    }
}
